/*
 * Copyright (c) 2018, apexes.net. All rights reserved.
 *
 *         http://www.apexes.net
 *
 */
package net.apexes.commons.lang;

/**
 * @author <a href="mailto:hedyn@foxmail.com">HeDYn</a>
 *
 */
public class PasswordsDemo {
    
    public static void main(String[] args) {
        try {
            // Print out 10 hashes
            for (int i = 0; i < 10; i++) {
                String password = sha1("12345678", 1);
                String digest = Passwords.digestBase58(password);
                System.out.println(password + " : " + digest + " : " + Passwords.validateBase58(password, digest));
            }

            // Test password validation
            boolean failure = false;
            System.out.println("Running tests...");
            for (int i = 0; i < 100; i++) {
                String password = md5("" + i, 3);
                String digest = Passwords.digest(password);
                String secondDigest = Passwords.digest(password);
                if (digest.equals(secondDigest)) {
                    System.out.println("FAILURE: TWO HASHES ARE EQUAL!");
                    failure = true;
                }
                String wrongPassword = md5("" + (i + 1), 3);
                if (Passwords.validate(wrongPassword, digest)) {
                    System.out.println("FAILURE: WRONG PASSWORD ACCEPTED!");
                    failure = true;
                }
                if (!Passwords.validate(password, digest)) {
                    System.out.println("FAILURE: GOOD PASSWORD NOT ACCEPTED!");
                    failure = true;
                }
            }
            if (failure) {
                System.out.println("TESTS FAILED!");
            } else {
                System.out.println("TESTS PASSED!");
            }
        } catch (Exception ex) {
            System.out.println("ERROR: " + ex);
        }
    }

    private static String md5(String password, int loop) {
        String result = password;
        for (int i = 0; i < loop; i++) {
            result = Secrets.md5Base58String(result);
        }
        return result;
    }

    private static String sha1(String password, int loop) {
        String result = password;
        for (int i = 0; i < loop; i++) {
            result = Secrets.sha1HexString(result);
        }
        return result;
    }

}
